import html2canvas from 'html2canvas';

export default function exportImage({el, type = 'png', scale = 1, name = 'default', success}) {
    if(typeof scale === 'string') {
        switch(scale) {
            case '2k' || '2K':
                scale = 3; break;
            case '4k' || '4K':
                scale = 5; break;
            case '1080P':
            default:
                scale = 1; break;
        }
    }
    html2canvas(document.querySelector(el), {
        scale
    }).then((canvas) => {
        const base64 = canvas.toDataURL('image/png');
        const oA = document.createElement('a');
        
        if(type == 'png') {
            oA.href = base64;
            oA.download = name + '.png';
        } else {
            oA.href = base64ToSvg(base64, canvas.width, canvas.height, scale);
            oA.download = name + '.svg';
        }
        
        document.body.appendChild(oA);
        oA.click();
        oA.remove();
        if(typeof success === "function") success();
    });
}

function base64ToSvg(base64, width, height, scale) {
    const svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
    svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
    svg.setAttribute('version', '1.1');
    svg.setAttribute('height', height / scale);
    svg.setAttribute('width', width / scale);
    let img = document.createElementNS('http://www.w3.org/2000/svg','image');
    img.href.baseVal = base64;
    //img.setAttribute('height', height);
    img.setAttribute('height', height / scale);
    img.setAttribute('width', width / scale);
    svg.appendChild(img);
    return 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svg.outerHTML)));
}